package com.ruoyi.quartz.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.domain.Holidays;
import org.apache.commons.compress.utils.Lists;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 调用API接口判断日期是否是工作日 周末还是节假日
 * 工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2
 */
public class HolidayUtil {

    private static String key = "7f345499688d1f43f36d63ebdeb71fbf";
    private static String httpUrl = "http://api.tianapi.com/txapi/jiejiari/index";

    public static List<Holidays> genHolidaysDate(int year) {
        StringBuffer sb = new StringBuffer();
        sb.append("key=" + key);
        sb.append("&type=1");
        sb.append("&date=" + year);
        String str = request(httpUrl, sb.toString());
        JSONObject jsonpObject = JSONObject.parseObject(str);
        JSONArray jsonArray = jsonpObject.getJSONArray("newslist");
        //节假日
        List<String> holidayList = new ArrayList<>();
        //补班
        List<String> makeWorkList = new ArrayList<>();
        jsonArray.forEach(p -> {
            JSONObject json = JSONObject.parseObject(p.toString());
            String[] holiday = json.getString("vacation").split("[|]");
            if(holiday.length > 0){
                holidayList.addAll(Arrays.asList(holiday));
            }
            String[] makeWork = json.getString("remark").split("[|]");
            if(makeWork.length > 0){
                makeWorkList.addAll(Arrays.asList(makeWork));
            }
        });

        return getDates(year, holidayList, makeWorkList);
    }

    /**
     * @param
     *            :请求接口
     * @param httpArg
     *            :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取某年内工作日、休息日、节假日
     *
     * @param year
     * @return
     */
    private static List<Holidays> getDates(int year, List<String> holiday, List<String> makeWork) {
        List<Holidays> dates = Lists.newArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 1; i <= 12; i++){
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, i - 1);
            cal.set(Calendar.DATE, 1);
            while (cal.get(Calendar.YEAR) == year && cal.get(Calendar.MONTH) < i) {
                int day = cal.get(Calendar.DAY_OF_WEEK);

                if ((day == Calendar.SUNDAY || day == Calendar.SATURDAY)) {
                    Date work = (Date) cal.getTime().clone();
                    Holidays day1 = new Holidays();
                    day1.setDate(work);
                    day1.setType(1);    //休息日
                    for (String hstr:holiday) {
                        if(hstr.equals(sdf.format(work))){
                            day1.setType(2);    //节假日
                        }
                    }
                    for (String wStr:makeWork) {
                        if(wStr.equals(sdf.format(work))){
                            day1.setType(0);    //补班
                        }
                    }

                    dates.add(day1);
                }else{
                    Date  work = (Date) cal.getTime().clone();
                    Holidays day1 = new Holidays();
                    day1.setDate(work);
                    day1.setType(0);
                    for (String hstr:holiday) {
                        if(hstr.equals(sdf.format(work))){
                            day1.setType(2);
                        }
                    }
                    dates.add(day1);
                }
                cal.add(Calendar.DATE, 1);
            }
        }

        return dates;

    }
}

